<template>
    <div>
        <el-button type="primary" @click="dialogVisible = true">上传图片</el-button>
        <el-dialog v-model="dialogVisible" title="选择图片" width="400px">
            <el-upload class="upload-demo" action="/api/upload" :show-file-list="false" :on-change="handleChange"
                :before-upload="beforeUpload" :http-request="customRequest" accept="image/*">
                <el-button>选择图片</el-button>
            </el-upload>
            <div v-if="imageUrl" style="margin-top:16px;text-align:center;">
                <img :src="imageUrl" alt="预览" style="max-width:100%;max-height:200px;" />
            </div>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" :disabled="!file" @click="uploadImage">上传</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const dialogVisible = ref(false)
const file = ref(null)
const imageUrl = ref('')

const handleChange = (uploadFile) => {
    file.value = uploadFile.raw
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const beforeUpload = (rawFile) => {
    if (!rawFile.type.startsWith('image/')) {
        ElMessage.error('只能上传图片文件！')
        return false
    }
    return true
}

const customRequest = () => { }

const uploadImage = async () => {
    if (!file.value) return
    const formData = new FormData()
    formData.append('file', file.value)
    try {
        await axios.post('/api/upload', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        ElMessage.success('上传成功！')
        dialogVisible.value = false
        file.value = null
        imageUrl.value = ''
    } catch (e) {
        ElMessage.error('上传失败')
    }
}
</script>